import { Component, OnInit, Input } from '@angular/core';
import { TreeModule, TreeNode, SelectItem, ConfirmationService } from 'primeng/primeng';
import { MdlSnackbarService } from '@angular-mdl/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FormDataPush } from '../fb-design.model';
import { FormDesignService } from '../fb-design.service';
@Component({
    selector: 'fb-datapush',
    templateUrl: './fb-datapush.component.html',
    styleUrls: ['./fb-datapush.component.scss'],
    providers: [FormDesignService]
})
export class FormDataPushComponent implements OnInit {
    formIdValue: number;
    datapushs: Array<FormDataPush>;
    formDataPush: FormDataPush = new FormDataPush();
    datapushForm: FormGroup;
    systemInfos: SelectItem[] = [];
    expressionTypes: SelectItem[] = new Array({ 'label': 'SQL', 'value': 'SQL' }, { 'label': 'JSON', 'value': 'JSON' });
    selectedExpressionType: SelectItem;
    datapushScrollHeight: string = '450px';
    selectedDataPush: FormDataPush;
    cols: any;

    @Input()
    set formId(formId: number) {
        if (!formId) return;
        this.formIdValue = formId;
        this.FormDesignService.listDataPush(formId)
            .subscribe(data => { this.datapushs = data })
    }

    get formId(): number {
        return this.formIdValue;
    }

    constructor(
        private fb: FormBuilder,
        private FormDesignService: FormDesignService,
        private mdlSnackbarService: MdlSnackbarService,
        private confirmationService: ConfirmationService) {
    }

    ngOnInit() {
        //初始化表头
        this.cols = [
            { field: 'dataPushId', header: '编号', style: { 'width': '80px', 'text-align': 'center' } },
            { field: 'dataPushName', header: '名称', style: { 'width': '200px', 'text-align': 'center' } },
            { field: 'systemName', header: '接口系统', style: { 'width': '200px', 'text-align': 'center' } },
            { field: 'expressionType', header: '抽取方式', style: { 'width': '100px', 'text-align': 'center' } },
            { field: 'dataExpression', header: '表达式', style: { 'overflow': 'hidden' } },
        ]
        //初始化数据源列表高度，自适应
        this.datapushScrollHeight = $("mdl-layout-content").height() - 230 + 'px';
        //初始化
        this.selectedExpressionType = this.expressionTypes[0];
        // this.FormDesignService.loadSystemInfoSelectItem()
        //     .subscribe(data => {
        //         data.forEach(ele => this.systemInfos.push({label: ele['systemName'], value: ele['systemId'], title: ele['systemUrl']}));
        //     });
        this.buildForm();
    }
    /**保存 */
    save() {
        let formDef =  this.datapushForm.value;
        formDef.formId = this.formIdValue;
        if(null == formDef.systemId)formDef.systemId = this.systemInfos[0].value;
        this.systemInfos.forEach(data => {
            if(formDef.systemId == data.value){
                formDef.systemName = data.label;
                formDef.systemUrl = data.title;
                return;
            }
        });
        formDef.expressionType = this.selectedExpressionType.value;
        this.FormDesignService.saveUpdateFormDataPush(formDef).subscribe(data => {
            this.FormDesignService.listDataPush(this.formIdValue).subscribe(data => {
                this.datapushs = data;
            });
        });
    }
    /**删除 */
    delete(rowData: any) {
        this.confirmationService.confirm({
            header: '确认',
            message: '您确定要删除这条记录吗？',
            accept: () => {
                this.FormDesignService.deleteDataPush(rowData.dataPushId)
                .subscribe(data => {
                    this.mdlSnackbarService.showToast("数据删除成功！");
                    this.FormDesignService.listDataPush(this.formId).subscribe(data => {
                        this.datapushs = data;
                    });
                    this.reset();
                })
            }
        });
    }
    /**验证 */
    validate(rowData: any) {

    }
    /**选择行 */
    onRowSelect($event) {
        this.selectedExpressionType = { label: '', value: '' };
        this.expressionTypes.forEach(ele => {
            if (this.selectedDataPush.expressionType == ele["value"]) {
                this.selectedExpressionType = ele;
                return;
            }
        });
        this.buildForm();
    }
    /**重置 */
    reset() {
        this.formDataPush = {};
        this.buildForm();
    }

    buildForm(): void {
        this.datapushForm = this.fb.group({
            'dataPushId': [this.formDataPush.dataPushId],
            'dataPushName': [this.formDataPush.dataPushName, [
                Validators.required,
                Validators.minLength(2),
                Validators.maxLength(20)
            ]
            ],
            'systemId': [this.formDataPush.systemId, Validators.required],
            'expressionType': [this.selectedExpressionType.value],
            'dataExpression': [this.formDataPush.dataExpression, [Validators.minLength(50), Validators.required]]
        });
        this.datapushForm.valueChanges
            .subscribe(data => this.onValueChanged(data));
        this.onValueChanged();
    }


    onValueChanged(data?: any) {
        if (!this.datapushForm) { return; }
        const form = this.datapushForm;

        for (const field in this.formErrors) {
            this.formErrors[field] = '';
            const control = form.get(field);
            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + ' ';
                }
            }
        }
    }

    formErrors = {
        'dataPushName': '',
        'dataExpression': ''
    };

    validationMessages = {
        'dataPushName': {
            'required': '请输入数据源名称',
            'minlength': '数据源名称长度必须大于2',
            'maxlength': '数据源名称长度必须小于20'
        },
        'dataExpression': {
            'required': '请输入获取数据SQL语句',
            'minlength': '获取数据SQL语句长度至少50个字符',
        }
    };
}
